package van.planifolia.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import van.planifolia.dao.BookDao;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Intellij IDEA<br>
 *
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/11/14 17:56
 */
@Service("bookService")
public class BookServiceImpl implements BookService{

    @Resource(name = "bookDao")
    private BookDao bookDao;

    /**
     * 用户买书的业务的方法
     * @param username 用户名
     * @param isbn 书本编号
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void buyBook(String username, String isbn) {
        // 首先我们查询一波这本书的价格
        int price = bookDao.selectBookPrice(isbn);
        // 然后我们验证库存是否够
        int stock = bookDao.selectBookStock(isbn);
        //若库存不够我们也是要抛出异常的
        if (stock <= 0){
            throw new RuntimeException("库存不足");
        }
        // 够的话库存减一
        bookDao.updateBookStock(isbn);
        // 然后我们验证当前用户的余额是否够买书的
        int balance = bookDao.selectAccount(username);
        if (balance < price){
            throw new RuntimeException("余额不足,无法购买");
        }
        // 够的话修改用户的余额
        bookDao.updateAccount(username,price);
        System.out.println("购书成功");
    }

    /**
     * 循环购书的方法
     * @param isbns 书的list
     * @param username 买书的用户
     */
    @Override
    @Transactional
    public void byBooks(List<String> isbns, String username) {
        for (String isbn : isbns) {
            this.buyBook(username,isbn);
        }
    }
}
